package com.teamin.service.impl.wx;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.teamin.web.Evn;
import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.locks.ReentrantLock;
import com.teamin.web.https.*;

/**
 * 微信开放平台
 *
 * @author 微信公众号,针对小程序
 *
 */
public class WeChatMPTokenManager {
	private Timer timer = new Timer();
	private static WeChatMPTokenManager tokenManager = null;
	private String accessToken = "";
	private long expiresIn;
	private Object accessLock = new Object();
	private boolean isGetAccessToken = false;
	// 公众号accesstoken
	private final String URL_ACCESS_TOKEN = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + Evn.APP_ID + "&secret=" + Evn.SECRET;
	ReentrantLock accessTokenWX = new ReentrantLock();

	private WeChatMPTokenManager() {

	}

	public static WeChatMPTokenManager getInstance() {
		// return tokenManager;
		synchronized (WeChatMPTokenManager.class) {
			if (tokenManager == null) {
				tokenManager = new WeChatMPTokenManager();
				tokenManager.setTimerByAccessToken(500);
			}
			return tokenManager;
		}
	}

	public JSONObject getUserByOpenId(String openId) {
		return HttpRequest.request("https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + getAccessToken() + "&openid=" + openId + "&lang=zh_CN", "GET", null);

	}

	public String getAccessToken() {

		synchronized (WeChatMPTokenManager.class) {
			if (isGetAccessToken) {
				try {
					accessLock.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}

		return accessToken;
	}

	private void getAccessTokenByWX() throws IOException {

		if("test".equals(Evn.SERVICE_PROFILS)) {
			return ;
		}

		if (accessTokenWX.tryLock()) {
			OkHttpClient okHttpClient = new OkHttpClient();
			Request request = new Request.Builder().url(URL_ACCESS_TOKEN).build();
			Call call = okHttpClient.newCall(request);
			Response response = call.execute();
			JSONObject asscessTokenObject =  JSON.parseObject(response.body().string());

			isGetAccessToken = true;
			if (asscessTokenObject != null && asscessTokenObject.containsKey("access_token")) {
				System.out.println(new Timestamp(System.currentTimeMillis()).toString() + "---------getAccess_token--------" + asscessTokenObject);
				accessToken = asscessTokenObject.getString("access_token");
				expiresIn = asscessTokenObject.getLong("expires_in");
				setTimerByAccessToken((expiresIn - 600) * 1000);
			} else {
				setTimerByAccessToken(5 * 1000);
			}
			isGetAccessToken = false;
			accessTokenWX.unlock();
			synchronized (accessLock) {
				accessLock.notifyAll();
			}

		}
	}

	public void setTimerByAccessToken(long delayTime) {

		//FIXME 小程序跟teamin共用一个公众号
		timer.schedule(new TimerTask() {

			@Override
			public void run() {
				try {
					getAccessTokenByWX();
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		}, delayTime);
	}

}
